package yxy.game.pm2.module.wuchao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.joda.time.DateTime;
import org.redisson.api.RBucket;
import yxy.apple.util.StringUtillity;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.glorywuchao;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.db.module.cache;
import yxy.game.pm2.bean.db.po.MailPo;
import yxy.game.pm2.bean.module.PlayerModule;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.module.mail.MailBean;
import yxy.game.pm2.module.mail.MailTypeEnum;
import yxy.game.pm2.module.shop.handle.WuchaoShopHandle;
import yxy.game.pm2.module.wuchao.event.WuchaoEvent;
import yxy.game.pm2.module.wuchao.event.WuchaoEventBoss;
import yxy.game.pm2.module.wuchao.event.WuchaoEventEnemy;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class WuchaoModule extends PlayerModule {
    // bean===========================================================================

    private int stage;// 当前层级
    private int bestStage;// 历史最高层级
    private int explore;// 探索度

    private int cure;// 金疮药数
    private int poison;// 毒药数

    private int passStage;// 通过的层数
    private ArrayList<Integer> box = new ArrayList<>();// 已经领取的宝箱

    private HashMap<String, WuchaoEvent> events = new HashMap<>();

    private HashMap<String, WuchaoHero> heros = new HashMap<>();// 武将快照

    public int getStage() {
        return stage;
    }

    public void setStage(int stage) {
        this.stage = stage;
    }

    public int getBestStage() {
        return bestStage;
    }

    public void setBestStage(int bestStage) {
        this.bestStage = bestStage;
    }

    public int getExplore() {
        return explore;
    }

    public void setExplore(int explore) {
        this.explore = explore;
    }

    public int getCure() {
        return cure;
    }

    public void setCure(int cure) {
        this.cure = cure;
    }

    public int getPoison() {
        return poison;
    }

    public void setPoison(int poison) {
        this.poison = poison;
    }

    public int getPassStage() {
        return passStage;
    }

    public void setPassStage(int passStage) {
        this.passStage = passStage;
    }

    public ArrayList<Integer> getBox() {
        return box;
    }

    public void setBox(ArrayList<Integer> box) {
        this.box = box;
    }

    public HashMap<String, WuchaoEvent> getEvents() {
        return events;
    }

    public void setEvents(HashMap<String, WuchaoEvent> events) {
        this.events = events;
    }

    public HashMap<String, WuchaoHero> getHeros() {
        return heros;
    }

    public void setHeros(HashMap<String, WuchaoHero> heros) {
        this.heros = heros;
    }

    // func===========================================================================

    public void init(Collection<WuchaoHero> heroList) {
        DateTime now = DateTime.now();
        timeline().setStartTime(now);
        timeline().setEndTime(now.withTimeAtStartOfDay().plusDays(2));
        setCure(4);
        setPoison(3);
        int startStage = getBestStage() - 5;
        startStage = startStage < 1 ? 1 : startStage;
        initStage(startStage);
        setPassStage(0);
        getBox().clear();
        getHeros().clear();
        for (WuchaoHero hero : heroList) {
            getHeros().put(hero.getCode(), hero);
        }

        set();
    }

    public void initStage(int stage) {
        Collection<glorywuchao> stagedatas = stageDatas(stage);
        if (stagedatas == null || stagedatas.size() <= 0) {
            return;
        }

        setStage(stage);
        setExplore(0);
        getEvents().clear();
        for (glorywuchao data : stagedatas) {
            String code = WuchaoEvent.randomCode(this);
            WuchaoEventEnemy event = null;
            if (data.getLevel() == 100) {
                event = WuchaoEventBoss.create(data);
            } else {
                event = WuchaoEventEnemy.create(data);
            }
            event.setCode(code);
            event.setLevel(data.getLevel());
            getEvents().put(event.getCode(), event);
        }
    }

    public Collection<glorywuchao> stageDatas(int stage) {
        ArrayList<glorywuchao> stagedatas = new ArrayList<>();
        Collection<glorywuchao> all = DataCenter.getAllData(glorywuchao.class).values();

        for (glorywuchao data : all) {
            if (data.getHierarchy() == stage) {
                stagedatas.add(data);
            }
        }
        return stagedatas;
    }

    private void update() {
        if (getTimeline() == null) {
            return;
        }
        if (!running()) {
            try {
                if (tryLock()) {
                    setTimeline(null);
                    setStage(0);
                    set();

                    new WuchaoShopHandle().getModule(getPlayerCode()).reset();
                }
            } catch (Exception e) {
            } finally {
                unlock();
            }
        }
    }

    // redis==========================================================================

    private static String key(String playerCode) {
        return String.format("PLAYER:%s:MODULE:WUCHAO", playerCode);
    }

    public void set() {
        try {
            setv(key(getPlayerCode()), this);
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    static public WuchaoModule get(String playerCode) {
        try {
            String key = key(playerCode);
            WuchaoModule module = getv(key);
            if (module == null) {
                //查数据库数据同步到redis
//                module = toBean(playerCode);
                if (module == null) module = create(playerCode);
            }
            module.update();
            return module;
        } catch (RedisException e) {
            e.printStackTrace();
        }
        return null;
    }

    static private WuchaoModule create(String playerCode) {
        WuchaoModule module = new WuchaoModule();
        module.setPlayerCode(playerCode);
        module.set();
        return module;
    }

    //存储到数据库的方法
    public static void saveToDB(String playerCode) {
        try {
            String key = key(playerCode);
            if (touchBucket(key).isExists()) {
                WuchaoModule wuchaoModule = getv(key(playerCode));
                MySQLCacheDAO.setV(key, wuchaoModule);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //从redis移走数据的操作
    public static void removeAllFromRedis(String playerCode) {
        try {
            touchBucket(key(playerCode)).delete();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }


    public static WuchaoModule toBean(String playerCode) {
        try {
            String key = key(playerCode);
            cache che = MySQLCacheDAO.get(key);
            if (che == null) return null;
            String value = che.getValue();
            if (StringUtillity.isEmpty(value)) return null;
            JSONObject object = JSONObject.parseObject(value);
            WuchaoModule module = new WuchaoModule();
            module.setPlayerCode(playerCode);
            module.setStage(object.getIntValue("stage"));
            module.setBestStage(object.getIntValue("bestStage"));
            module.setExplore(object.getIntValue("explore"));
            module.setCure(object.getIntValue("cure"));
            module.setPoison(object.getIntValue("poison"));
            module.setPassStage(object.getIntValue("passStage"));
            ArrayList<Integer> boxList = JSON.parseObject(object.getString("box"), new TypeReference<ArrayList<Integer>>() {
            });
            module.setBox(boxList);


            HashMap<String, WuchaoEvent> eventMap = JSON.parseObject(
                    object.getString("events"),
                    new TypeReference<HashMap<String, WuchaoEvent>>() {
                    }
            );
            module.setEvents(eventMap);

            HashMap<String, WuchaoHero> heroMap = JSON.parseObject(
                    object.getString("heros"),
                    new TypeReference<HashMap<String, WuchaoHero>>() {
                    }
            );
            module.setHeros(heroMap);
            System.out.println("WuchaoModuleFromTableEnd");
            return module;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    // lock==========================================================================

    @Override
    public String lockKey() {
        return String.format("lock:%s", key(getPlayerCode()));
    }

    @Override
    public String toString() {
        return "WuchaoModule{" +
                "stage=" + stage +
                ", bestStage=" + bestStage +
                ", explore=" + explore +
                ", cure=" + cure +
                ", poison=" + poison +
                ", passStage=" + passStage +
                ", box=" + box +
                ", events=" + events +
                ", heros=" + heros +
                ", playerCode=" + this.getPlayerCode() +
                '}';
    }
}
